//
//  SearchCellTag.swift
//  clreader
//
//  Created by colin on 2019/3/27.
//  Copyright © 2019 colin. All rights reserved.
//

extension SearchViewController {
    
    class CellTag: UITableViewCell {
        
        enum TagType {
            case hotkey
            case history
        }
        
        static let reuseId = "CellTag"
        var cellHeight:CGFloat = 0
        
        private var tags = [String]()
        private var searchHandle:((_ keyword:String)->Void)?
        private var clearHandle:(()->Void)?
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.selectionStyle = .none
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func refresh(type:TagType, tags:[String],searchHandle:((_ keyword:String)->Void)?,clearHandle:(()->Void)? = nil) {
            
            self.tags = tags
            self.clearHandle = clearHandle
            self.searchHandle = searchHandle
            
            self.cellHeight = 0
            for subview in self.contentView.subviews {
                subview.removeFromSuperview()
            }
            if tags.isEmpty {
                return
            }
            
            // 标题
            let labelTitle = UILabel().then {
                $0.text = type == .hotkey ? "热门搜索" : "搜索历史"
                $0.textColor = UIColor(hex: "343434")
                $0.font = UIFont.systemFont(ofSize: 17.0, weight: .bold)
            }
            self.contentView.addSubview(labelTitle)
            labelTitle.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15.0)
                make.top.equalToSuperview().offset(28.0)
            }
            
            // 清空
            if type == .history {
                let buttonClear = UIButton(type: .custom).then {
                    $0.setTitle("清空", for: .normal)
                    $0.setTitleColor(UIColor(hex: "828282"), for: .normal)
                    $0.titleLabel?.font = UIFont.systemFont(ofSize: 15.0, weight: .light)
                    $0.addTarget(self, action: #selector(self.actionClear(_:)), for: .touchUpInside)
                }
                self.contentView.addSubview(buttonClear)
                buttonClear.snp.makeConstraints { (make) in
                    make.right.equalToSuperview()
                    make.size.equalTo(CGSize(width: 44.0, height: 44.0))
                    make.top.equalToSuperview().offset(14.0)
                }
            }
            
            var x:CGFloat = 0
            var y:CGFloat = 0
            var containerHeight:CGFloat = 0
            let containerWidth = UIScreen.main.bounds.width - 15.0 - 15.0
            let itemHeight:CGFloat = 34.0
            let distance:CGFloat = 15.0
            
            let tagsContainer = UIView().then {
                $0.backgroundColor = UIColor.white
                
                for index in 0 ..< tags.count {
                    
                    let item = UIView().then {
                        $0.backgroundColor = UIColor(hex: "EFEFEF")
                        $0.layer.cornerRadius = 17.0
                        $0.layer.masksToBounds = true
                        $0.tag = index
                        $0.isUserInteractionEnabled = true
                        let tap = UITapGestureRecognizer(target: self, action: #selector(self.actionTap(_:)))
                        $0.addGestureRecognizer(tap)
                        
                        
                        let labelTag = UILabel().then {
                            $0.text = tags[index]
                            $0.textColor = UIColor(hex: "343434")
                            $0.font = UIFont.systemFont(ofSize: 14.0, weight: .light)
                        }
                        $0.addSubview(labelTag)
                        labelTag.snp.makeConstraints({ (make) in
                            make.left.equalToSuperview().offset(15.0)
                            make.right.equalToSuperview().offset(-15.0)
                            make.centerY.equalToSuperview()
                        })
                        
                    }
                    $0.addSubview(item)
                    
                    // 计算当前的位置
                    let currentWidth = tags[index].size(font: UIFont.systemFont(ofSize: 14.0, weight: .light), containerWidth: CGFloat.greatestFiniteMagnitude).width + 15.0 + 15.0
                    if x == 0 && y == 0 {
                        containerHeight += itemHeight
                    }
                    if x + currentWidth + distance > containerWidth {
                        // 容器高度
                        containerHeight += itemHeight + distance
                        
                        // 需要换行
                        x = 0
                        y += itemHeight + distance
                    }
                    
                    item.snp.makeConstraints({ (make) in
                        make.left.equalToSuperview().offset(x)
                        make.top.equalToSuperview().offset(y)
                        make.height.equalTo(itemHeight)
                    })
                    
                    // 计算下一个的位置
                    if x + currentWidth + distance > containerWidth {
                        // 需要换行
                        x = 0
                        y += itemHeight + distance
                    } else {
                        x += currentWidth + distance
                    }
                }
            }
            self.contentView.addSubview(tagsContainer)
            tagsContainer.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(72.0)
                make.left.equalToSuperview().offset(15.0)
                make.right.equalToSuperview().offset(-15.0)
                make.height.equalTo(containerHeight)
            }
            
            self.cellHeight = 72.0
            self.cellHeight += containerHeight
        }
        
        @objc private func actionTap(_ sender:UIGestureRecognizer?) {
            if let index = sender?.view?.tag, index < self.tags.count {
                self.searchHandle?(self.tags[index])
            }
        }
        
        @objc private func actionClear(_ sender:Any) {
            self.clearHandle?()
        }
        
    }
    
}
